import {
  Controller,
  UseGuards,
  Request,
  Get,
  Param,
  Delete,
  Body,
  Post,
  HttpException,
  HttpStatus,
  Patch,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Result } from 'src/common/Result';
import { CreateWorkspaceDto } from './dto/createWorkspace.dto';
import { WorkspaceService } from './workspace.service';

@ApiTags('工作区')
@Controller('workspace')
export class WorkspaceController {
  constructor(private readonly workspaceService: WorkspaceService) {}

  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  @Get('/')
  async findAll(@Request() req): Promise<Result> {
    const id = req.user.userId;
    const data = await this.workspaceService.getWorkspaceByUid(id);
    return {
      message: '成功',
      data,
    };
  }

  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  @Get(':workspaceId')
  async findDetail(@Param('workspaceId') wid: string): Promise<Result> {
    const data = await this.workspaceService.getWorkspaceDetail(wid);
    return {
      message: '成功',
      data,
    };
  }

  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  @Delete(':workspaceId')
  async remove(@Param('workspaceId') wid: string): Promise<Result> {
    await this.workspaceService.deleteWorkspace(wid);
    return {
      message: '成功',
    };
  }

  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  @Post('/')
  async create(
    @Body() createWorkspaceDto: CreateWorkspaceDto,
    @Request() req,
  ): Promise<Result> {
    const id = req.user.userId;
    const hasSame = await this.workspaceService.hasEqual(
      createWorkspaceDto,
      id,
    );

    if (hasSame) {
      throw new HttpException(
        {
          message: '已经存在相同的workspace',
        },
        HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
      );
    } else {
      await this.workspaceService.create(createWorkspaceDto, id);
      return {
        message: '创建成功',
      };
    }
  }

  @ApiBearerAuth()
  @UseGuards(AuthGuard('jwt'))
  @Patch(':workspaceId')
  async modifyName(
    @Body() createWorkspaceDto: CreateWorkspaceDto,
    @Request() req,
    @Param('workspaceId') wid: string,
  ) {
    const id = req.user.userId;
    const hasSame = await this.workspaceService.hasEqual(
      createWorkspaceDto,
      id,
    );

    if (hasSame) {
      throw new HttpException(
        {
          message: '已经存在相同的workspace',
        },
        HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
      );
    } else {
      await this.workspaceService.modifyName(createWorkspaceDto, wid);
      return {
        message: '修改成功',
      };
    }
  }
}
